import { defineStore } from "pinia";
import { computed,  shallowRef} from "vue";
import { ApiFunc } from "../../api";
import{arrToTree}from '../../utils/public'

const SysFuncs={
  func:"系统功能管理",
  role:"系统角色管理",
  user:"系统用户管理",
  staff:"员工管理",
  classroom:"教室管理",
  class:"班级管理",
  student:"学生管理"
}
//shuzu转树
// const arr2tree = (arr: Array<UI.Func>): UI.FuncTree | null => {
//   if (!Array.isArray(arr)) {
//     throw new Error("我要一个数组");
//   }
//   function _arr2tree(fid: number): UI.FuncTree | null {
//     let nodes = arr.filter((item) => item.func_fid === fid);
//     if (nodes.length === 0) {
//       return null;
//     }
//     return nodes.reduce((result: UI.FuncTree, node: any) => {
//       let newNode: UI.FuncTreeItem = { ...node };
//       let children = _arr2tree(newNode.func_id);
//       if (children) {
//         newNode.children = children;
//       }
//       result.push(newNode);
//       return result;
//     }, []);
//   }
//   return _arr2tree(0);
// };


export const useFuncStore = defineStore("func", () => {
  const allFuncs = shallowRef<Array<UI.Func>>([]);
  const funcTree = computed<UI.FuncTree>(() => {
    let root: UI.FuncTreeItem = {
      func_id: 0,
      func_name: "root",
      func_key: "",
      func_fid: -1,
    };
    let children = arrToTree(allFuncs.value,'func_id','func_fid',0);
    if (children) root.children = children;
    return [root];
  });
  const funcTreeWithNoLeaf = computed<UI.FuncTree>(() => {
    let root: UI.FuncTreeItem = {
      func_id: 0,
      func_name: "root",
      func_key: "",
      func_fid: -1,
    };
    let children = arrToTree(
      allFuncs.value.filter((item) => item.func_key === ""),
      "func_id",
      "func_fid",
      0
    );
    if (children) root.children = children;
    return [root];
  });
  // const staffStatusList=computed(()=>{list.value.filter(item=>item.dic_group_key==="staff_status")})
  const updateFunc = async (func: API.Func.Update) => {
    await ApiFunc.update(func);
    allFuncs.value = await ApiFunc.get();
  };
const addFunc=async(func:API.Func.Add)=>{
  await ApiFunc.add(func)
  allFuncs.value=await ApiFunc.get()
}
  ApiFunc.get().then((data) => (allFuncs.value = data));

  return { allFuncs, funcTree, funcTreeWithNoLeaf, updateFunc, addFunc,SysFuncs };
},
  

);
